import Request from 'luch-request'
import Qs from 'qs'
import getSign from "./sign"
import store from '../store/index'

const serve = new Request();

serve.setConfig((config) => { /* config 为默认全局配置*/
	config.baseURL = 'https://bookserver.sanye666.top'; /* 根域名 */
	config.header = {
		'content-type': 'application/x-www-form-urlencoded'
	};
	timeout: 5000
	return config
})

serve.interceptors.request.use((config) => {
	let timeStramp = Math.round(new Date().getTime() / 1000).toString();
	let sign = getSign(timeStramp);
	config.data = { ...config.data,
		timeStramp,
		sign
	};
	config.data = Qs.stringify(config.data);
	return config
}, config => {
	return Promise.reject(config)
})

serve.interceptors.response.use((response) => {
	const res = response;
	if (res.data.code !== 200) {
		if (res.data.code == 1001) { //密码错误
			uni.showToast({
				title: res.data.msg || '账号/密码错误',
				duration: 2000,
				icon: 'none'
			});
			return Promise.reject(res);
		}
		if (res.data.code == 1003) {
			uni.showToast({
				title: res.data.msg || '验证码发送过于频繁，请稍后再试',
				duration: 2000,
				icon: 'none'
			});
			return Promise.reject(res);
		}
		if (res.data.code == 400) {
			uni.showToast({
				title: res.data.msg || '网络出错了',
				duration: 2000,
				icon: 'none'
			});
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 1000);
			return Promise.reject(res);
		}
		if (res.data.code == 401) {
			uni.showToast({
				title: 'token失效了',
				duration: 2000,
				icon: 'none'
			})
			store.dispatch('resetToken').then(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			})
			return Promise.reject(res);
		}
		uni.showToast({
			title: res.data.msg || '服务器出错了',
			duration: 2000,
			icon: 'none'
		});
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/index/index'
			});
		}, 1000)
		return Promise.reject(res);
	} else {
		return res.data;
	}
}, (response) => {
	if(response.data.code == 401){
		uni.showToast({
			title: '登陆信息过期了,请重新登陆',
			duration: 2000,
			icon: 'none'
		});
		store.dispatch('resetToken').then(() => {
			uni.navigateTo({
				url: '/pages/user/login'
			});
		})
	}
	return Promise.reject(response);
})

export default serve
